package com.taoz.rpc.core.loadbalancer;

import cn.hutool.core.collection.CollUtil;
import com.taoz.rpc.core.model.ServiceMetaInfo;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class RoundRobinLoadBalancer implements LoadBalancer {

    private final AtomicInteger count = new AtomicInteger(0);

    @Override
    public ServiceMetaInfo selectService(List<ServiceMetaInfo> serviceList, Map<String, Object> balanceParams ) {
        log.info("正在使用 {} 获取服务", "RoundRobinLoadBalancer");
        if (CollUtil.isEmpty(serviceList)) {
            return null;
        } else if (serviceList.size() == 1) {
            return serviceList.get(0);
        }
        int index = count.getAndIncrement();
        return serviceList.get(index % serviceList.size());
    }
}
